// pages/law/clist/index.js
import util from '../../../utils/util';

var _levelTwoObj = null;
var _selectedIndex = 0;
var _typeIndexMap = {
  0: 10,
  1: 20,
  2: 30
}
var _levelTwoSelectedID, _levelThreeSelectedID, _levelFourSelectedID;

function _getCategoryBySelectedIDs(_ids, _index, _subIndex, _obj){
  if(_index >= _ids.length-1) return;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/bd/categories`, 
      //仅为示例，并非真实的接口地址
      data: {
        pid: _index==-1 ? null : _ids[_index],
        type: _typeIndexMap[_subIndex]
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        res.data = res.data || [];
        for(var i=0; i<res.data.length; i++){
            if(res.data[i].id == _ids[_index+1]){
              res.data[i].selected = true;
            }
        }
        switch(_index){
          case -1: _obj.setData({
            levelTwo: res.data || []
          }); break;
          case 0: _obj.setData({
            levelThree: res.data || []
          }); break;
          case 1: _obj.setData({
            levelFour: res.data || []
          }); break;
        }

        _getCategoryBySelectedIDs(_ids, ++_index, _subIndex, _obj);
      },
      fail: function(res){
        console.log(res);
      }
    });
}

function _getCategoryAndDetail(_index, _subIndex, _pid, _obj){
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/bd/categories`, 
      //仅为示例，并非真实的接口地址
      data: {
        pid: _pid,
        type: _typeIndexMap[_subIndex]
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        switch(_index){
          case 1: _obj.setData({
            levelTwo: res.data || []
          }); break;
          case 2: _obj.setData({
            levelThree: res.data || []
          }); break;
          case 3: _obj.setData({
            levelFour: res.data || []
          }); break;
        }
      },
      fail: function(res){
        console.log(res);
      }
    });
}

function _getSelectedObj(_data){
  var _returnArr = [];
  if(_data.levelTwo.length > 0){
    for(var i=0; i<_data.levelTwo.length; i++){
      if(_data.levelTwo[i].selected){
        _returnArr.push(_data.levelTwo[i]);
      }
    }
  }

  if(_data.levelThree.length > 0){
    for(var i=0; i<_data.levelThree.length; i++){
      if(_data.levelThree[i].selected){
        _returnArr.push(_data.levelThree[i]);
      }
    }
  }

  if(_data.levelFour.length > 0){
    for(var i=0; i<_data.levelFour.length; i++){
      if(_data.levelFour[i].selected){
        _returnArr.push(_data.levelFour[i]);
      }
    }
  }

  return _returnArr;
}


// 通过category idstr 获取detail
function _filterDetailByCategoryIDs(_cid, _pIndex, _pSize, _pageObj){
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    duration: 10000
  });
  wx.request({
    url: `${getApp().globalData.serverHost}/wx/bd/filter`, 
    //仅为示例，并非真实的接口地址
    data: {
      ids: _cid,
      pIndex: _pIndex,
      pSize: _pSize
    },
    method: "post",
    header: {
        'content-type': 'application/json'
    },
    success: function(res) {
      wx.hideToast();
      _pageObj.hideFilter();

      var _list = [];
      if(_pIndex > 1){
        _list = _pageObj.data.list || [];
      }

      if(!!res && !!res.data && !!res.data.detail && !!res.data.detail.length){
        for(var j=0; j<res.data.detail.length; j++){
              res.data.detail[j].publishTime = util.formatCommonShortTime(res.data.detail[j].publishTime);
              res.data.detail[j].effectiveTime = util.formatCommonShortTime(res.data.detail[j].effectiveTime);
          }

        _list = _list.concat(res.data.detail || []);
      }else{
         wx.showToast({
          title: _pIndex==1 ? '没有查到相关法条' : '没有更多内容',
          icon: 'success',
          duration: 2000
        });
      }

      _pageObj.setData({
          list: _list
        });
    },
    fail: function(res){
      console.log(res);
    }
  });
}

// 获取最新列表
function _getDetailList(_pIndex, _pSize,_pageObj){
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    duration: 10000
  });
  wx.request({
    url: `${getApp().globalData.serverHost}/wx/bd/law/newest`, 
    //仅为示例，并非真实的接口地址
    data: {
      pIndex: _pIndex,
      pSize: _pSize
    },
    method: "post",
    header: {
        'content-type': 'application/json'
    },
    success: function(res) {
      wx.hideToast();
      _pageObj.hideFilter();

      var _list = _pageObj.data.list || [];

      if(!!res && !!res.data){
        for(var j=0; j<res.data.detail.length; j++){
              res.data.detail[j].publishTime = util.formatCommonShortTime(res.data.detail[j].publishTime);
              res.data.detail[j].effectiveTime = util.formatCommonShortTime(res.data.detail[j].effectiveTime);
          }

        _list = _list.concat(res.data.detail || []);

        _pageObj.setData({
          list: _list
        });
      }
    },
    fail: function(res){
      console.log(res);
    }
  });
}

var _levelOne = [{
  id: 10,
  name: "效力级别",
  selectedName: "选择",
  selectedID: null,
  selected: []
},{
  id: 20,
  name: "发布部门",
  selectedName: "选择",
  selectedID: null,
  selected:[]
},{
  id: 30,
  name: "法规类别",
  selectedName: "选择",
  selectedID: null,
  selected: []
}];

Page({
  data:{
    pageSize: 30,
    scrollHeight: 500,
    scrollTop: 0,
    showFilter: true
  },
  onLoad:function(options){
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      name: options.name,
      maskHide: true,
      dialogHide: true,
      levelOne: _levelOne,
      filterTitle: "查询"
    });

    var that = this;
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/get/kv`, 
      //仅为示例，并非真实的接口地址
      data: {
        key: 'levelOneCategory'
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        _levelOne = JSON.parse(res.data.value);
        that.setData({
          levelOne: _levelOne
        })
      },
      fail: function(res){
        console.log(res);
      }
    });

    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight: res.windowHeight-45
        });
      }
    });
  },
  bindLevelTwo: function(_event){
    var _index = _event.currentTarget.dataset.index;
    for(var i=0; i<this.data.levelTwo.length; i++){
      if(this.data.levelTwo[i].selected && i == _index) break;
      this.data.levelTwo[i].selected = false;
      if(i == _index){
        this.data.levelTwo[i].selected = true;
        _levelTwoSelectedID = this.data.levelTwo[i].id;
      }
    }
    this.setData({
      levelTwo: this.data.levelTwo
    });

    this.setData({
      levelFour: []
    });

    _getCategoryAndDetail(2, _index, this.data.levelTwo[_index].id, this);
  },
  bindLevelThree: function(_event){
    var _index = _event.currentTarget.dataset.index;
    for(var i=0; i<this.data.levelThree.length; i++){
      if(this.data.levelThree[i].selected && i == _index) break;
      this.data.levelThree[i].selected = false;
      if(i == _index){
        this.data.levelThree[i].selected = true;
        _levelThreeSelectedID = this.data.levelThree[i].id;
      }
    }
    this.setData({
      levelThree: this.data.levelThree
    });

    this.setData({
      levelFour: []
    });

    _getCategoryAndDetail(3, _index, this.data.levelThree[_index].id, this);
  },
  bindLevelFour: function(_event){
    var _index = _event.currentTarget.dataset.index;
    for(var i=0; i<this.data.levelFour.length; i++){
      if(this.data.levelFour[i].selected && i == _index) break;
      this.data.levelFour[i].selected = false;
      if(i == _index){
        this.data.levelFour[i].selected = true;
        _levelFourSelectedID = this.data.levelFour[i].id;
      }
    }
    this.setData({
      levelFour: this.data.levelFour
    });
  },
  showFilter: function(){
    this.setData({
      showFilter: true
    });
  },
  hideFilter: function(){
    this.setData({
      showFilter: false
    });
  },
  showFilterDialog: function(_event){
    this.setData({
      maskHide: false,
      dialogHide: false
    });
    _selectedIndex = _event.currentTarget.dataset.index;
    this.setData({
      levelTwo: [],
      levelThree: [],
      levelFour: []
    });

    var _selectedArr = this.data.levelOne[_selectedIndex].selected || [];
    if(_selectedArr.length >0){
      var _ids = [];
      for(var i=0; i<_selectedArr.length; i++){
        _ids.push(_selectedArr[i].id);
      }
      _getCategoryBySelectedIDs(_ids, -1, _selectedIndex, this);
    }else{
      _getCategoryAndDetail(1, _selectedIndex, null, this);
    }
  },
  hideMask: function(){
    this.setData({
      dialogHide: true
    });
    var that = this;
    setTimeout(function(){
      that.setData({
        maskHide: true
      });
    }, 400);
  },
  dialogGoBack: function(){
    this.hideMask();
  },
  dialogConfirm: function(){
    var _arr = _getSelectedObj(this.data);
    if(!!_arr.length){
      _levelOne[_selectedIndex].selected = _arr;
      _levelOne[_selectedIndex].selectedID = _arr[_arr.length-1].id;
      var _names = [];
      for(var i=0; i<_arr.length; i++){
        _names.push(_arr[i].name);
      }
      _levelOne[_selectedIndex].selectedName = _names.join("-");
    }else{
      _levelOne[_selectedIndex].selected = [];
      _levelOne[_selectedIndex].selectedID = null;
      _levelOne[_selectedIndex].selectedName = "选择";
    }
    this.setData({
      levelOne: _levelOne
    });
    this.hideMask();
  },
  clearSelected: function(){
    if(this.data.levelTwo.length > 0){
      for(var i=0; i<this.data.levelTwo.length; i++){
        this.data.levelTwo[i].selected = false;
      }
    }
    if(this.data.levelThree.length > 0){
      for(var i=0; i<this.data.levelThree.length; i++){
        this.data.levelThree[i].selected = false;
      }
    }
    if(this.data.levelFour.length > 0){
      for(var i=0; i<this.data.levelFour.length; i++){
        this.data.levelFour[i].selected = false;
      }
    }
    this.setData({
      levelTwo: this.data.levelTwo,
      levelThree: this.data.levelThree,
      levelFour: this.data.levelFour
    });
  },
  filterDetail: function(){
    var _ids = [];
    for(var i=0; i<this.data.levelOne.length; i++){
      if(!!this.data.levelOne[i].selectedID){
        _ids.push(this.data.levelOne[i].selectedID);
      }
    }
    var _idStr = _ids.join(",");
    this.setData({
      pIndex: 1,
      pSize: 20,
      selectedIDStr: _idStr
    });
    if(!_idStr){
      _getDetailList(this.data.pIndex, this.data.pSize, this);
    }else{
      _filterDetailByCategoryIDs(_idStr, this.data.pIndex, this.data.pSize, this);
    }
  },
  loadMore: function(){
    // 获取列表
    this.setData({
      pIndex: this.data.pIndex+1
    });
    _filterDetailByCategoryIDs(this.data.selectedIDStr, this.data.pIndex, this.data.pageSize, this);
  },
  scroll:function(event){
    //   该方法绑定了页面滚动时的事件，我这里记录了当前的position.y的值,为了请求数据之后把页面定位到这里来。
     this.setData({
         scrollTop : event.detail.scrollTop
     });
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
    this.setData({
      maskHide: true,
      dialogHide: true
    })
  },
  onUnload:function(){
    // 页面关闭
    this.setData({
      maskHide: true,
      dialogHide: true
    })
  }
})